import pinyin
from ldap3 import Server, Connection

class LDAP(object):
    def __init__(self, host, port, base_dn, user, password):
        dn = 'cn={},{}'.format(user, base_dn)
        self.server = Server(host=host, port=port)
        self.base_dn = base_dn
        self.__conn = Connection(self.server, dn, password, auto_bind=True)

    def add_user(self, userid, username, position, department):
        uidNumber = '%s' % userid[-4:]
        objectclass = ['top', 'inetOrgPerson', 'posixAccount']

        # 只将研发人员加入ldap
        # 分组名称与ldap分组名称保持一致
        position = position.replace('组', '')
        if position not in ['产品', '后端', '前端', '测试', '设计', '中台']:
            return "Other"

        # 获取项目组gidNumber
        if position not in ['产品', '后端', '前端']:
            search_dn = 'cn={},cn=产品研发,ou=People,{}'.format(position, self.base_dn)
            dn = 'cn={},cn={},cn=产品研发,ou=People,{}'.format(username, position, self.base_dn)
        else:
            search_dn = 'cn={},cn={},cn=产品研发,ou=People,{}'.format(position, department, self.base_dn)
            dn = 'cn={},cn={},cn={},cn=产品研发,ou=People,{}'.format(username, position, department, self.base_dn)
        filter = '(cn={})'.format(position)
        status = self.__conn.search(search_dn, filter, attributes=['gidNumber'])
        if status:
            data = self.__conn.entries
            gidNumber = data[0].entry_attributes_as_dict["gidNumber"]
        else:
            return " Gid Error"

        # 添加新入职员工
        s = self.__conn.add(dn, objectclass, {
            'sn': pinyin.get(username[0], format='strip').encode('utf-8'),
            'cn': username.encode('utf-8'),
            'uid': pinyin.get(username, format='strip').encode('utf-8'),
            'gidNumber': gidNumber,
            'homeDirectory': '/home/users/%s' % pinyin.get(username, format='strip').encode('utf-8'),
            'loginShell': '/usr/sbin/nologin'.encode('utf-8'),
            'uidNumber': uidNumber.encode('utf-8'),
            'userPassword': '123456'.encode('utf-8'),
        })
        return s

    # 删除离职员工
    def delete_user(self, username, position, department):
        # 分组名称与ldap名称保持一致
        position = position.replace('组', '')
        if position not in ['产品', '后端', '前端', '测试', '设计', '中台']:
            return "Other"

        if position not in ['产品', '后端', '前端']:
            dn = 'cn={},cn={},cn=产品研发,ou=People,{}'.format(username, position, self.base_dn)
        else:
            dn = 'cn={},cn={},cn={},cn=产品研发,ou=People,{}'.format(username, position, department, self.base_dn)
        d = self.__conn.delete(dn)
        return d

